#coding:utf8
# user=None
# 只要你采用了jwt的认证,登录成功之后,会调用此方法,此方法就把认证的用户信息,传递过来了
def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'user_id':user.id,
        'username':user.username
    }



from django.contrib.auth.backends import ModelBackend
import re
from users.models import User

# 1. 原有的认证方式 不能满足我们的需求,所以要找到原有的认证

# 2. 我们输入手机号/用户名,因为手机号和用户名是一对一的关系,所以可以根据手机号找到用户

# account -->手机号/用户名
def get_user_by_account(account):

    try:
        if re.match(r'1[3-9]\d{9}',account):
            #手机号
            user = User.objects.get(mobile=account)
        else:

            #用户名
            user = User.objects.get(username=account)
    except User.DoesNotExist:

        user = None


    return user


# 3. 根据查询的用户信息区检测密码是否正确

class UsernameMobleAuth(ModelBackend):

    # username=None, password=None 就是在登录的时候输入的
    def authenticate(self, request, username=None, password=None, **kwargs):

        user = get_user_by_account(username)

        if user is not None and user.check_password(password):
            #没有问题就返回用户信息
            return user

        return None


class SettingsBackend(object):
    """
    Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.

    Use the login name and a hash of the password. For example:

    ADMIN_LOGIN = 'admin'
    ADMIN_PASSWORD = 'pbkdf2_sha256$30000$Vo0VlMnkR4Bk$qEvtdyZRWTcOsCnI/oQ7fVOu1XAURIZYoOZ3iq8Dr4M='
    """

    def authenticate(self, request, username=None, password=None):

        user = get_user_by_account(username)

        if user is not None and user.check_password(password):
            return user

        return None


    #继承子object的类需要多实现一个方法 get_user(self, user_id)

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
